<template>
  <div class="login-container">
    <van-nav-bar title="头条-登录" fixed />
    <van-form @submit="login">
      <van-field
        v-model="form.mobile"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="form.code"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/userAPI.js'
export default {
  name: 'Login',
  data() {
    return {
      form: {
        mobile: '13888888888',
        code: '246810'
      },
      rules: {
        mobile: [
          { required: true, message: '请填写您的手机号', trigger: 'onBlur' },
          {
            pattern: /^1\d{10}$/,
            message: '请填写正确的手机号',
            trigger: 'onBlur'
          }
        ],
        code: [{ required: true, message: '请填写您的密码', trigger: 'onBlur' }]
      }
    }
  },

  components: {},

  computed: {},

  mounted() {},

  methods: {
    async login() {
      const { data: res } = await loginAPI(this.form)
      if (res.message === 'OK') {
        // 把登录接口返回的 token 存放到vuex
        this.$store.commit('updateTokenInfo', res.data)
        // 处理登录成功后，跳转回登录之前的页面
        console.log('query pre:', this.$route)
        if (this.$route.query.pre) {
          // 证明 pre 这个参数有对应的值
          this.$router.push(this.$route.query.pre)
        } else {
          // pre 这个参数的值不存在
          this.$router.push('/')
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  padding-top: 92px;
  height: 3000px;
}
</style>
